<template>
  <div>
    <a-modal title="导入核算表" :maskClosable="false" :visible="visible" @ok="handleOk" @cancel="handleCancel" :confirmLoading="confirmLoading">
      <a-spin :spinning="confirmLoading">
        <j-form-container :disabled="false">
          <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item label="导入的核算表月份" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salaryPeriod">
                  <j-month-date
                    placeholder="请选择导入的核算表月份"
                    v-model="model.salaryPeriod"
                    :disabledDate="disabledDate"
                    style="width: 100%;" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="社保单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="insuranceUnit">
                  <select-Company-input placeholder="请选择社保单位" urlList="/api/erp/files/employee/erpEmployeePostChangeRecord/queryCompanyByPost" v-model="model.insuranceUnit"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-upload
                  name="file"
                  :showUploadList="false"
                  :data="additionalData"
                  :multiple="false"
                  :headers="tokenHeader"
                  :action="importExcelUrl"
                  @change="handleImportExcel">
                  <a-button type="primary" icon="import" :disabled="disabled">导入核算表</a-button>
                </a-upload>
              </a-col>
              <a-col :span="24">
                <span style="font-size: 12px; color: red;">选择核算表后，薪资数据将自动上传并更新</span>
              </a-col>
            </a-row>
          </a-form-model>
        </j-form-container>
      </a-spin>
      <template slot="footer">
        <a-button key="back" @click="handleCancel">关闭</a-button>
      </template>
    </a-modal>
  </div>
</template>
<script>
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput' // 公司
import moment from 'moment'
import Vue from 'vue'
import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types'
import { Modal } from 'ant-design-vue'
import store from '@/store'
export default {
  name: 'ErpSalaryAccountingRecordImportModal',
  components: {
    SelectCompanyInput
  },
  data() {
    return {
      model: {
        salaryPeriod: '',
        insuranceUnit: ''
      },
      labelCol: {
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      validatorRules: {
        salaryPeriod: [
          { required: false, message: '请选择导出的核算表月份!' }
        ],
        insuranceUnit: [
          { required: false, message: '请选择社保单位!' }
        ]
      },
      url: {
        importExcelUrl: '/api/erp/salacct/erpSalaryAccountingRecord/importExcelAndCalc'
      },
      visible: false,
      confirmLoading: false
    };
  },
  computed: {
    disabled () {
      // 当导入的核算表月份和社保单位有值时可以点击反之禁用
      return !(this.model.salaryPeriod && this.model.insuranceUnit)
    },
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`;
    },
    // token header
    tokenHeader() {
      let head = {
        'Authorization': Vue.ls.get(ACCESS_TOKEN),
        'client-id': 'web',
        'user-id': Vue.ls.get('user_id') || ''

      }
      let tenantid = Vue.ls.get(TENANT_ID)
      if (tenantid) {
        head['tenant_id'] = tenantid
      }
      return head
    },
    additionalData () {
      // 导入时传递的额外参数
      return {
        salaryPeriod: this.model.salaryPeriod,
        insuranceUnit: this.model.insuranceUnit
      }
    }
  },
  methods: {
    // 禁用
    disabledDate(current) {
      const date = new Date()
      let month = date.getMonth()
      // 禁用当前月份和之后的所有月份
      return current.month() >= month
    },
    showModal() {
      this.model = {
        salaryPeriod: moment().subtract(1, 'month').format('YYYY-MM'),
        insuranceUnit: ''
      }
      this.visible = true;
    },
    // 导入
    handleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let {
              message,
              result: { msg, fileUrl, fileName }
            } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: (
                <div>
                  <span> {msg} </span>
                  <br />
                  <span>
                    {' '}
                    具体详情请{' '}
                    <a href={href} target="_blank" download={fileName}>
                      {' '}
                      点击下载{' '}
                    </a>{' '}
                  </span>
                </div>
              )
            })
          } else {
            this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
          }
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}`)
        }
      } else if (info.file.status === 'error') {
        if (info.file.response.status === 500) {
          let data = info.file.response
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token && data.message.includes('Token失效')) {
            Modal.error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload()
                })
              }
            })
          }
        } else {
          this.$message.error(`文件上传失败: ${info.file.msg} `)
        }
      }
    },

    handleOk(e) {
      this.visible = false;
      this.confirmLoading = false;
    },
    handleCancel(e) {
      this.visible = false;
    }
  }
};
</script>
